package com.huiquan.zs.controller;

import com.huiquan.analysis.constants.AnalysisSentenceConstant;
import com.huiquan.analysis.domain.AnalysisSearchParam;
import com.huiquan.analysis.domain.User;
import com.huiquan.common.Pair;
import com.huiquan.framework.base.BaseController;
import com.huiquan.framework.base.ReturnData;
import com.huiquan.framework.utils.RequestParamUtil;
import com.huiquan.sphinx.SphinxException;
import com.huiquan.util.StringUtil;
import com.huiquan.zs.service.ZsSentenceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class ZsSentenceController extends BaseController {

    @Autowired
    private ZsSentenceService zsSentenceService;

    /**
     * 获取主诉未标注列表
     *
     * @return
     * @throws SphinxException
     */
    @RequestMapping(value = "/zs/sentence_unlabel_list.htm")
    public ModelAndView sentenceUnlabelList(String tabid) {
        // 获取PageParam和SearchParams
        Pair<Map<String, Object>, List<AnalysisSearchParam>> pair = getPageParamAndSearchParams(tabid);
        // 获取页面参数，如果request中有值则修改session，否则从session中拿值
        String start = RequestParamUtil.getParamByRequestOrSession(getRequest(), pair.first, "start");
        Map<String, Object> map = zsSentenceService.sentenceUnlabelList(start, pair.second);
        return new ModelAndView("zs/sentence_unlabel_list", map);
    }

    /**
     * 获取主诉已标注列表
     *
     * @param tabid
     * @return
     * @throws SphinxException
     */
    @SuppressWarnings("unchecked")
    @RequestMapping(value = "/zs/sentence_labeled_list.htm")
    public ModelAndView sentenceLabeledList(String tabid) {
        // 获取PageParam和SearchParams
        Pair<Map<String, Object>, List<AnalysisSearchParam>> pair = getPageParamAndSearchParams(tabid);
        // 获取页面参数，如果request中有值则修改session，否则从session中拿值
        String start = RequestParamUtil.getParamByRequestOrSession(getRequest(), pair.first, "start");
        Map<String, Object> map = zsSentenceService.sentenceLabeledList(start, pair.second);
        return new ModelAndView("zs/sentence_labeled_list", map);
    }

    /**
     * 获取主诉已删除列表
     *
     * @param tabid
     * @return
     * @throws SphinxException
     */
    @SuppressWarnings("unchecked")
    @RequestMapping(value = "/zs/sentence_del_list.htm")
    public ModelAndView deleteList(String tabid) {
        int type;
        Map<String, Object> pageParam;
        if (StringUtil.isNotEmpty(tabid)) {
            pageParam = new HashMap<>();
            pageParam.put("tabid", tabid);
            pageParam.put("exactSearchFlag", "0");
            setSessionValue("pageParam", pageParam);
        } else {
            pageParam = (Map<String, Object>) getSessionValue("pageParam");
        }

        // 获取页面参数，如果request中有值则修改session，否则从session中拿值
        String start = RequestParamUtil.getParamByRequestOrSession(getRequest(), pageParam, "start");
        String sentence = RequestParamUtil.getParamByRequestOrSession(getRequest(), pageParam, "sentence");
        String exactSearchFlag = RequestParamUtil.getParamByRequestOrSession(getRequest(), pageParam, "exactSearchFlag");
        Map<String, Object> map = zsSentenceService.zsDeleteList(start, sentence, exactSearchFlag);
        return new ModelAndView("zs/sentence_del_list", map);
    }


    /**
     * 删除主诉
     *
     * @param idStr
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/zs/sentence_delete.do")
    public ReturnData deleteZs(@RequestParam("id") String idStr) {
        return zsSentenceService.deleteZs(idStr);
    }

    /**
     * 保留主诉
     *
     * @param idStr
     * @return
     */
    @SuppressWarnings("unchecked")
    @ResponseBody
    @RequestMapping(value = "/zs/sentence_recover.do")
    public ReturnData recoverZs(@RequestParam("id") String idStr) {
        ReturnData result = zsSentenceService.recoverZs(idStr);
        zsSentenceService.asynchronousUpdateSphinxIndex("vocabulary" + AnalysisSentenceConstant.TYPE_ZS + "_delta");
        return result;
    }

    /**
     * 进入主诉未标记词语编辑画面
     *
     * @return
     */
    @RequestMapping(value = "/zs/sentence_unlabel_pre_edit.htm")
    public ModelAndView zsUnlabelPreEdit(@RequestParam("id") String idStr) {
        //获取数据的方式跟已标注的方式一样，显示界面不同
        Map<String, Object> map = zsSentenceService.zsPreEdit(idStr);
        return new ModelAndView("zs/sentence_unlabel_pre_edit", map);
    }

    /**
     * 进入主诉已标记词语编辑画面
     *
     * @return
     */
    @RequestMapping(value = "/zs/sentence_labeled_pre_edit.htm")
    public ModelAndView zsLabeledPreEdit(@RequestParam("id") String idStr) {
        Map<String, Object> map = zsSentenceService.zsPreEdit(idStr);
        return new ModelAndView("zs/sentence_labeled_pre_edit", map);
    }


    /**
     * 进行词语编辑操作
     *
     * @param id
     * @return
     * @throws Exception
     */
    @SuppressWarnings("unchecked")
    @ResponseBody
    @RequestMapping(value = "/zs/sentence_edit.do")
    public ReturnData edit(String id) throws Exception {
        User user = (User) getSessionValue("user");
        Map<String, Object> map = getRequest().getParameterMap();
        String[] vocabularyStrs = (String[]) map.get("vocabulary");
        String[] characterStrs = (String[]) map.get("character");
        String[] propertyStrs = (String[]) map.get("property");
        String[] position1Strs = (String[]) map.get("position1");
        String[] position2Strs = (String[]) map.get("position2");
        String[] sourceStrs = (String[]) map.get("source");

        return zsSentenceService.edit(AnalysisSentenceConstant.TYPE_ZS + "", "", id, user, vocabularyStrs, characterStrs,
                propertyStrs, position1Strs, position2Strs, getRequest(), sourceStrs);
    }

    /**
     * 获取PageParam和SearchParams
     *
     * @param tabid
     * @return
     */
    @SuppressWarnings("unchecked")
    private Pair<Map<String, Object>, List<AnalysisSearchParam>> getPageParamAndSearchParams(String tabid) {
        List<AnalysisSearchParam> searchParams = new ArrayList<>(); // 多词语查询
        if (StringUtil.isNotEmpty(tabid)) {
            Map<String, Object> pageParam = new HashMap<>();
            pageParam.put("tabid", tabid);
            setSessionValue("pageParam", pageParam);
            return new Pair<>(pageParam, searchParams);
        }
        Map<String, Object> pageParam = (Map<String, Object>) getSessionValue("pageParam");
        Map<String, Object> map = getRequest().getParameterMap();
        String[] vocabularyKeys = (String[]) map.get("vocabularyKey");
        if (vocabularyKeys != null && vocabularyKeys.length > 0) {
            String[] propertyKeys = (String[]) map.get("propertyKey");
            String[] position1Keys = (String[]) map.get("position1Key");
            String[] position2Keys = (String[]) map.get("position2Key");
            String[] oppositePropertyFlagKeys = (String[]) map.get("oppositePropertyFlagKey");
            String[] oppositePosition1FlagKeys = (String[]) map.get("oppositePosition1FlagKey");
            for (int i = 0; i < vocabularyKeys.length; i++) {
                if (!vocabularyKeys[i].trim().isEmpty()) {
                    AnalysisSearchParam searchParam = new AnalysisSearchParam();
                    searchParam.setId((long) i);
                    searchParam.setVocabulary(vocabularyKeys[i].trim());
                    searchParam.setProperty(propertyKeys[i] == null ? null : propertyKeys[i].trim());
                    searchParam.setPosition1(position1Keys[i] == null ? null : position1Keys[i].trim());
                    searchParam.setPosition2(position2Keys[i] == null ? null : position2Keys[i].trim());
                    searchParam.setOppositePropertyFlag(oppositePropertyFlagKeys[i]);
                    searchParam.setOppositePosition1Flag(oppositePosition1FlagKeys[i]);
                    searchParams.add(searchParam);
                }
            }
            pageParam.put("searchParams", searchParams);
        }
        if (searchParams.isEmpty()) {
            searchParams = (List<AnalysisSearchParam>) pageParam.get("searchParams");
        }
        return new Pair<>(pageParam, searchParams);
    }
}
